package com.kun.controller.admin;

import com.alibaba.fastjson.JSON;
import com.kun.entity.Blog;
import com.kun.result.Result;
import com.kun.service.impl.BlogServiceImpl;
import com.kun.service.impl.CommentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @descriptions: 后台博客管理
 * @author: SunKun
 * @date: 2021/7/9 0009 18:02
 * @version: 1.0
 */
@RestController
@CrossOrigin  //允许跨域
@ResponseBody
@RequestMapping("/kun/admin/blog")
public class BlogAdminController {
    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private CommentServiceImpl commentService;

    /**
     * 增加博客
     * @param blog
     * @return
     */
    @PostMapping("/insertBlog")
    public Result insertBlog(@RequestBody Blog blog){
        try {
            int i = blogService.insertBlog(blog);
            if(i > 0) {
                //发布成功后，将博客的相关信息放到lucene索引库中
//                blogIndex.addIndex(blog);
                return Result.ok();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error();
    }

    /**
     * 查询博客详情
     * @param param
     * @return
     */
    @PostMapping("/selectBlogById")
    public Result selectBlogById(@RequestBody Map<String,Object> param){
        int id = (int)param.get("blogId");
        try {
            Blog blog = blogService.selectBlogById(id);
            return Result.ok().data("blog",blog);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * 更改博客
     * @param blog
     * @return
     */
    @PostMapping("/updateBlogById")
    public Result updateBlogById(@RequestBody Blog blog){
        return blogService.updateBlogById(blog) != 0 ? Result.ok() : Result.error();
    }

    /**
     * 批量更新
     * @param param
     * @return
     * 前端后端 数组并不能交互
     * 所以前端需要将数组 转换为json格式的字符串
     */
    @PostMapping("/batchUpdateBlog")
    public Result batchUpdateBlog(@RequestBody Map<String,Object> param){
        String blogs = (String) param.get("blogs");
        //后端将接收的json格式字符串转换为list集合
        List<Blog> blogList = JSON.parseArray(blogs, Blog.class);
        return blogService.batchUpdateBlog(blogList) != 0 ? Result.ok() : Result.error();
    }

    /**
     * 批量删除
     * @param param
     * @return
     */
    @PostMapping("/batchDeleteBlog")
    public Result batchDeleteBlog(@RequestBody Map<String,Object> param){
        String blogs = (String) param.get("blogs");
        //后端将接收的json格式字符串转换为list集合
        List<Blog> blogList = JSON.parseArray(blogs, Blog.class);
        for (Blog blog : blogList){
            commentService.delComment(blog.getId());
        }
        return blogService.batchDeleteBlog(blogList) != 0 ? Result.ok() : Result.error();
    }
}
